# 113. 路径总和 II

// 给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
// 叶子节点 是指没有子节点的节点。
var pathSum = function(root, targetSum) {
  if (!root) return [];
  let resArr = [];

  dfs(root, 0, []);

  function dfs(node, num, res) {
    if (!node.left && !node.right) {
      if (num + node.val === targetSum) resArr.push([...res, node.val]);
      return;
    }

    if (
      (targetSum >= 0 && num + node.val > targetSum) ||
      (targetSum < 0 && num + node.val < targetSum)
    )
      return;

    node.left && dfs(node.left, num + node.val, [...res, node.val]);
    node.right && dfs(node.right, num + node.val, [...res, node.val]);
  }

  return resArr;
};

console.log(
  pathSum(
    {
      val: 5,
      left: {
        val: 4,
        left: {
          val: 11,
          left: {
            val: 7,
          },
          right: {
            val: 2,
          },
        },
      },
      right: {
        val: 8,
        left: {
          val: 13,
        },
        right: {
          val: 4,
          left: {
            val: 5,
          },
          right: {
            val: 1,
          },
        },
      },
    },
    22
  )
);
console.log(
  pathSum(
    {
      val: 1,
      left: {
        val: 2,
      },
      right: {
        val: 3,
      },
    },
    5
  )
);
console.log(
  pathSum(
    {
      val: 1,
      left: {
        val: 2,
      },
    },
    0
  )
);
console.log(pathSum(null, 0));
console.log(
  pathSum(
    {
      val: -2,
      right: {
        val: -3,
      },
    },
    -5
  )
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
Last Updated: 6/27/2023, 7:40:45 PM